package com.wxc.exception.handler;


import com.wxc.exception.BusinessException;
import com.wxc.vo.REnum;
import com.wxc.vo.Resp;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.List;


/**
 * @author wxc
 * @date 2021年09月02日 13:50
 * 全局处理异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Resp<String> exceptionHandler(Exception e) {
        log.error("Exception,{}", e.toString());
        return Resp.error(REnum.ERROR);
    }

    @ExceptionHandler(BusinessException.class)
    public Resp<String> businessExceptionHandler(BusinessException e) {
        // log.error("BusinessException,{}", Arrays.toString(e.getStackTrace()));
        log.error("BusinessException,{}", e.getMessage());
        return Resp.error(e.getREnum());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Resp<String> bindExceptionHandler(MethodArgumentNotValidException e) {
        String defaultMessage = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        log.error("MethodArgumentNotValidException,{}", defaultMessage);
        // 参数校验失败:用户名不能为空
        String message = REnum.BIND_ERROR.getMessage() + ":" + defaultMessage;
        return Resp.error(REnum.BIND_ERROR.getCode(), message,null);
    }

    /**
     * @date 2021/10/24 21:40
     * @param e
     * 权限不足
     */
    @ExceptionHandler(UnauthorizedException.class)
    public Resp<String> businessExceptionHandler(UnauthorizedException e) {
        // log.error("BusinessException,{}", Arrays.toString(e.getStackTrace()));
        log.error("UnauthorizedException,{}", e.getMessage());
        return Resp.error(REnum.AUTHORIZATION_ERROR);
    }
}
